package com.dapeng.jackson.serializer;

import com.dapeng.jackson.abstracts.BaseJKAnnotationSerializer;
import com.dapeng.jackson.annotations.JKDecimalFormat;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * @BelongProject study
 * @BelongPackage com.dapeng.jackson.serializer
 * @Description TODO
 * @ClassName JKDecimalScaleSerializer
 * @Author xupenghong
 * @Date 2024/9/13 16:01
 * @Version 1.0.0
 */
public class JKDecimalScaleSerializer extends BaseJKAnnotationSerializer<JKDecimalFormat, Number> {

    @Override
    public void serialize(Number number, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        if (number == null) {
            return;
        }

        int scale = annotation.scale();
        boolean smartScale = annotation.smartScale();

        BigDecimal value;
        if (fieldClass == BigDecimal.class) {
            value = (BigDecimal) number;
        } else if (fieldClass == Float.class) {
            value = BigDecimal.valueOf((Float) number);
        } else if (fieldClass == Double.class) {
            value = BigDecimal.valueOf((Double) number);
        } else {
            jsonGenerator.writeString(number.toString());
            return;
        }

        if (smartScale) {
            String str = smartScale(value, scale);
            jsonGenerator.writeNumber(new BigDecimal(str));
        } else {
            jsonGenerator.writeNumber(value.setScale(scale, RoundingMode.HALF_UP));
        }
    }
}
